package com.bobbygu.bobbyapp.function.replugin

import android.util.Log
import com.alibaba.fastjson.JSON
import com.bobbygu.libnet.utils.ACache
import com.bobbygu.bobbyapp.base.MyApplication
import com.bobbygu.bobbyapp.bean.PluginBean
import com.bobbygu.bobbyapp.network.HttpAction
import com.bobbygu.bobbyapp.utils.FileUtils
import com.orhanobut.logger.Logger

/**
 * 插件化 数据层
 * # time: 2017/11/29 13:40
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since 1.0
 */
class RepluginModel : RepluginContract.Model() {
    override fun downloadPlugin(url: String) {
        Logger.d("downloadPlugin:" + url)

        postDownload(url, { responseBody ->
            Log.d("UploadModel", "responseBody:" + responseBody)
            val bs = responseBody.byteStream()
            val fileName = url.substring(url.lastIndexOf('/') + 1)
            val bytes = FileUtils.getBytes(bs)
            val filePath = FileUtils.writeTempData(MyApplication.getInstance(), bytes, fileName)
            viewModel.returnFilePath(fileName, filePath)
        }, null, { bytesRead, contentLength, done ->
            Logger.d("bytesRead:$bytesRead contentLength:$contentLength done:$done")
            viewModel.returnDownloadProgress((bytesRead * 100 / contentLength).toInt())
        })
    }

    override fun getPluginMsg() {
        post(HttpAction.GetPluginMsg, { jsonObject ->
            val list = JSON.parseArray(jsonObject.getJSONArray("data").toJSONString(), PluginBean::class.java)
            for (plugin in list) {
                if (ACache.get(MyApplication.getInstance()).getAsString(plugin.name) != null)
                    plugin.buttonName = "打开"
                else
                    plugin.buttonName = "安装"
            }
            viewModel.returnPluginList(list)
        }, null)
    }
}